package com.qlm.service.impl;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.qlm.common.Define;
import com.qlm.entity.Order;
import com.qlm.entity.Exchangerecord;
import com.qlm.entity.Gift;
import com.qlm.service.IGiftService;
import com.qlm.tools.Common;
import com.qlm.tools.QiniuUtil;
import com.qlm.view.ResultMessage;

/**
 * 积分礼品配置接口实现类
 * 
 * @author raoy
 *
 */
public class GiftServiceImpl implements IGiftService {

	protected final static Logger logger = LoggerFactory
			.getLogger(GiftServiceImpl.class);

	public static String Gift_TABLE_NAME = "t_jf_gift";
	public static String Gift_PRIMARY_KEY = "id";
	private static ResultMessage resultMessage = new ResultMessage();

	@Override
	@Before(Tx.class)
	public ResultMessage saveGiftInfo(Gift giftInfo, UploadFile imgFile,UploadFile details_img) {
		String img = "";

		if (imgFile != null) {
			resultMessage = saveImgFile(imgFile);
			if (resultMessage.getState() == Define.RM_SUCCESS) {
				img = QiniuUtil.IMAGEURL+resultMessage.getData().toString();
			} else {
				return resultMessage;
			}
		}
		

		giftInfo.set("img_", img);
		giftInfo.set("time_", Common.nowDate());
		giftInfo.set("online_", 0);

		boolean result = Db.save("t_gift", "id",
				giftInfo.toRecord());

		if (result) {
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "保存积分礼品配置信息成功");
		} else {
			return ResultMessage.setAllMessage(Define.RM_FAIL, "保存积分礼品配置信息失败");
		}
	}

	@Override
	public ResultMessage updateGiftInfo(Gift giftInfo,String details_img_,UploadFile imgFile) {				
		// 获取原来的信息,并将更新后的信息合并进去
		Gift newGift = Gift.Dao.findById(giftInfo.get("id").toString());
		//判断详情图片是否修改
		if(Common.isNullOrEmpty(imgFile) && Common.isEmptyString(details_img_)){//未修改
			newGift.set("img_", details_img_);
		}else if(!Common.isNullOrEmpty(imgFile) && !Common.isEmptyString(details_img_)){//上传新图片
			resultMessage = saveImgFile(imgFile);
			if (resultMessage.getState() == Define.RM_SUCCESS) {
				String img = QiniuUtil.IMAGEURL+resultMessage.getData().toString();
				newGift.set("img_", img);
			} else {
				return resultMessage;
			}			
		}else if(Common.isNullOrEmpty(imgFile) && !Common.isEmptyString(details_img_)){//删除详情图片
			//newGift.set("img_", null);
		}else{
			return ResultMessage.setAllMessage(Define.RM_FAIL, "网络连接错误，请稍后再试");			
		}
		
		newGift.set("name_", giftInfo.get("name_"));
		newGift.set("desc_", giftInfo.get("desc_"));
		newGift.set("price_", giftInfo.get("price_"));

		boolean result = Db.update("t_gift", "id",
				newGift.toRecord());

		if (result) {
			callCache("cache/updateGift");
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "更新积分礼品配置信息成功");
		} else {
			return ResultMessage.setAllMessage(Define.RM_FAIL, "更新积分礼品配置信息失败");
		}
	}

	@Override
	public ResultMessage deleteGiftInfo(String id) {
		List<Exchangerecord> list = findSendGiftID(id);
		if(!Common.isNullOrEmpty(list) && list.size()!=0){			
			Gift ex = new Gift();
			ex.set("is_delete", 1).set("id", id).update();
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "删除积分礼品配置信息成功");
		}
		List<Order> couponList = findSendCouponListByGiftID(id,
				Define.COUPON_STATUS_RECEIVE);
		if (couponList.size() != 0) {
			Gift ex = new Gift();
			ex.set("is_delete", 1).set("id", id).update();
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "删除积分礼品配置信息成功");
		}
		boolean result = Db.deleteById(Gift_TABLE_NAME, Gift_PRIMARY_KEY, id);
		boolean result2 = true;
		
		couponList = findSendCouponListByGiftID(id,Define.COUPON_STATUS_UNCLAIMED);
		if(couponList.size() != Define.COUPON_STATUS_UNCLAIMED){
			result2 = deleteCouponInfoByGiftID(id);
		}
		
		
		if (result && result2) {
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "删除积分礼品配置信息成功");
		} else {
			return ResultMessage.setAllMessage(Define.RM_FAIL, "删除积分礼品配置信息失败");
		}
	}

	@Override
	public List<Gift> getGiftInfoList() {
		// TODO Auto-generated method stub
		return Gift.Dao
				.find("select *  from t_gift order by time_ desc");
	}

	@Override
	public Gift getGiftInfoById(String id) {
		// TODO Auto-generated method stub
		return Gift.Dao.findById(id);
	}

	@Override
	public ResultMessage updateStateById(String id, int state) {
		int status = 0;

		int count = Db.update("update t_gift set online_ = "+state+" where id = "+id);

		if (count > 0) {
			callCache("cache/updateGift");
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "积分礼品状态更新成功", status);
		} else {
			return ResultMessage.setAllMessage(Define.RM_FAIL, "积分礼品状态更新失败", state);
		}
	}

	/**
	 * 上传图片文件到七牛云
	 * @param imgFile 图片文件
	 * @return
	 */
	private static ResultMessage saveImgFile(UploadFile imgFile) {
			String fileName = Common.getStringFullDate() + imgFile.getFileName(); // 文件名称
	
			try {
				String success = QiniuUtil.upload(imgFile.getFile().getPath(),
						fileName); // 上传到七牛云服务
				if (success != null) {
					imgFile.getFile().delete(); // 如果上传成功，就删除本地服务的图片
					return ResultMessage.setAllMessage(Define.RM_SUCCESS, "上传图片成功。", fileName);
				} else {
					return ResultMessage.setAllMessage(Define.RM_FAIL, "未能将图片上传至七牛云服务器，上传图片失败，请重试或联系网站管理员。");
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return ResultMessage.setAllMessage(Define.RM_FAIL, "上传图片失败，请重试或联系网站管理员。");
			}		
	}

	private static ResultMessage saveImgFile(String fileName ,UploadFile imgFile) {

		try {
			QiniuUtil.delete(fileName);
			String success = QiniuUtil.upload(imgFile.getFile().getPath(),
					fileName); // 上传到七牛云服务
			if (success != null) {
				imgFile.getFile().delete(); // 如果上传成功，就删除本地服务的图片
				return ResultMessage.setAllMessage(Define.RM_SUCCESS, "上传图片成功。", fileName);
			} else {
				return ResultMessage.setAllMessage(Define.RM_FAIL, "未能将图片上传至七牛云服务器，上传图片失败，请重试或联系网站管理员。");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.setAllMessage(Define.RM_FAIL, "上传图片失败，请重试或联系网站管理员。");
		}		
}
	public ResultMessage updateImgById(String id, UploadFile fileImg) {
		String Img = "";
		
		if(fileImg == null){
			return ResultMessage.setAllMessage(Define.RM_FAIL, "上传图片失败，请稍后重试或联系网站管理员。");
		}
		resultMessage = saveImgFile(fileImg);

		if (resultMessage.getState() == Define.RM_SUCCESS) {
			Img = QiniuUtil.IMAGEURL+resultMessage.getData().toString();
		} else {
			return resultMessage;
		}

		int count = Db.update("update t_gift set img_ = '"+Img+"' where id = "+id);

		if (count > 0) {
			callCache("cache/updateGift");
			return ResultMessage.setAllMessage(Define.RM_SUCCESS, "更新积分礼品状态图片信息成功");
		} else {
			return ResultMessage.setAllMessage(Define.RM_FAIL, "更新积分礼品状态图片信息失败");
		}
	}

	@Override
	@Before(Tx.class)
	public boolean updateGiftCount(int number, String id) {

		int count = Db
				.update("update "
						+ Gift_TABLE_NAME
						+ " set count = count + ?, remain_count = remain_count + ? where "
						+ Gift_PRIMARY_KEY + " = ?", number, number, id);

		if (count > 0) {
			callCache("cache/updateGift");
			return true;
		} else {
			return false;
		}
	}

	@Override
	@Before(Tx.class)
	public boolean updateGiftRemainCount(int number, String id) {
		// TODO Auto-generated method stub
		int count = Db.update("update " + Gift_TABLE_NAME
				+ " set remain_count = remain_count + ? where "
				+ Gift_PRIMARY_KEY + " = ?", number, id);

		if (count > 0) {
			callCache("cache/updateGift");
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 根据礼品ID和coupon状态查找对应的coupon信息
	 * @param giftID 礼品ID
	 * @param status coupon状态（领取：1或未领取：0）
	 * @return
	 */
	private static List<Order> findSendCouponListByGiftID(String giftID,int status){
		return Order.Dao.find(
				"select id,gift_id,coupon,status,create_time,draw_time from "
						+ CouponServiceImpl.COUPON_TABLE_NAME
						+ " where gift_id = ? and status = ?", giftID, status);
	}
	
	/**
	 * 删除与giftID对应的coupon信息
	 * @param giftID 
	 * @return
	 */
	private static boolean deleteCouponInfoByGiftID(String giftID){
		boolean flag = false;
		int result = Db.update("delete from " + CouponServiceImpl.COUPON_TABLE_NAME + " where gift_id = ?", giftID);
		if(result > 0){
			callCache("cache/updateGift");
			 flag =true;
		}
		return flag;
	}
	
	/**
	 * 
	 */
	private static List<Exchangerecord> findSendGiftID(String id){
		return Exchangerecord.dao.find("select id from t_jf_exchange where gift_id=?",id);
	}
	
	/**
	 * 发送请求给cache更新
	 * @param type
	 */
	public static void callCache(String type){
			new Thread(new Runnable() {
				public void run() {
					String cacheUrl = PropKit.get("cacheUrl");
					String[] urlArr = cacheUrl.split(",");
					try{						
						for(int i=0;i<urlArr.length;i++){
							if(Common.isEmptyString(urlArr[i])){
								HttpKit.get(urlArr[i] + type);
								logger.info(urlArr[i]+type+"请求发送成功");
							}							
						}
					}catch(Exception e){
						logger.error(e.getMessage(), e);
					}							
				}
			}).start();
	}
}
